import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'dart:ui';

import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/video_upload_success_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/service/media_library_index_service.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_matisse_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:path_provider/path_provider.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

class UploadMediaLibraryService {
  ///App公司添加播放资源库
  static const String _UPLOAD_MEDIA_LIBRARY_API =
     ServerApi.BASE_URL + "app/appUploadComPicurl";

  List<UploadMediaLibraryItemBean> _uploadList;
  
  String _hsn;

  ///设置值
  UploadMediaLibraryService setList(List<UploadMediaLibraryItemBean> folderList,String hsn) {
    if (folderList == null || folderList.isEmpty) {
      return null;
    }
    if(hsn == null){
      return null;
    }
    _hsn = hsn;
    _uploadList = folderList;
    return this;
  }

  void upload(VgBaseCallback<List<UploadMediaLibraryItemBean>> callback) async {
    if (_uploadList == null || _uploadList.isEmpty) {
      callback?.onError("需要上传的数据为空");
      return;
    }
    try {
      for (UploadMediaLibraryItemBean item in _uploadList) {
        item = await _manageFolder(item);
      }
    }catch(e){
      callback?.onError("处理出现异常");
      print("上传报错:$e");
      return;
    }
    _uploadList.removeWhere((element) => element == null);
    print("打印需要上传的信息：$_uploadList");
    List<Future<UploadMediaLibraryItemBean>> futureList = List();
    for (UploadMediaLibraryItemBean item in _uploadList) {
      futureList.add(_httpFolder(item));
    }
    Future.wait(futureList)..then((List<UploadMediaLibraryItemBean> list){
     callback?.onSuccess(list);
    }).catchError((e){
      callback?.onError("个别文件上传失败");
    });
  }

  ///处理文件
  Future<UploadMediaLibraryItemBean> _manageFolder(
      UploadMediaLibraryItemBean item) async {
    if (item == null ||
        item.mediaType == null ||
        StringUtils.isEmpty(item.localUrl)) {
      return null;
    }
    if (item.isImage()) {
      return _decodeImage(item);
    }
    if (item.isVideo()) {
      return await _decodeVideo(item);
    }
    return null;
  }

  UploadMediaLibraryItemBean _decodeImage(UploadMediaLibraryItemBean item) {
    if (item == null ||
        item.mediaType == null ||
        StringUtils.isEmpty(item.localUrl)) {
      return null;
    }

    File file = File(item.localUrl);
    item.folderStorage = file.lengthSync();

    FileImage image = FileImage(File(item.localUrl));
    // 预先获取图片信息
    image
        .resolve(new ImageConfiguration())
        .addListener(new ImageStreamListener((ImageInfo info, bool _) {
      item.folderWidth = info.image.width;
      item.folderHeight = info.image.height;
      return item;
    }));
  }

  Future<UploadMediaLibraryItemBean> _decodeVideo(
      UploadMediaLibraryItemBean item) async {
    if (item == null ||
        item.mediaType == null ||
        StringUtils.isEmpty(item.localUrl)) {
      return null;
    }
    File file = File(item.localUrl);
    Directory rootPath = await getTemporaryDirectory();
    Directory tempDirectory = new Directory('${rootPath.path}/imageTemp');
    if (!tempDirectory.existsSync()) {
      tempDirectory.createSync();
    }
    String tmpVideoCover = await VideoThumbnail.thumbnailFile(
      video: item.localUrl,
      thumbnailPath: tempDirectory?.path,
      imageFormat: ImageFormat.JPEG,
      maxWidth: 1920,
      quality: 100,
    );
    item.videoLocalCover = tmpVideoCover;
    //
    VideoPlayerController videoController = VideoPlayerController.file(file);
    await videoController.initialize();
    item.videoDuration = videoController?.value?.duration?.inSeconds;
    item.folderWidth = videoController?.value?.size?.width?.floor();
    item.folderHeight = videoController?.value?.size?.height?.floor();
    item.folderStorage = file.lengthSync();
    videoController.dispose();
    return item;
  }

  Future<UploadMediaLibraryItemBean> _httpFolder(UploadMediaLibraryItemBean item) async {
    if (item == null) {
      return null;
    }
    if (item.isImage()) {
      try {
        item.netUrl = await VgMatisseUploadUtils.uploadSingleImageForFuture(
            item.localUrl,
            isNoCompress: false);
        item.folderName=item?.getFolderNameStr() ?? "";
        return _httpUpload(item);
      } catch (e) {
        print("上传单图异常：$e");
      }
    }

    if (item.isVideo()) {
      try {
        VideoUploadSuccessBean successBean = await VgMatisseUploadUtils.uploadSingleVideoForFuture(
            item.localUrl);
        item.netUrl = successBean.url;
        item.videoid = successBean.videoid;
        if(!StringUtils.isEmpty(successBean.fileSize)){
          item.folderStorage = int.parse(successBean.fileSize);
        }
        item.folderName = VgMatisseUploadUtils.getVideoPath();
        item.videoNetCover =
            await VgMatisseUploadUtils.uploadSingleImageForFuture(
                item.videoLocalCover,
                isNoCompress: false);
        return _httpUpload(item);
      } catch (e) {
        print("UploadMediaLibraryService上传异常：$e");
      }
    }
    return null;
  }

  Future<UploadMediaLibraryItemBean> _httpUpload(UploadMediaLibraryItemBean item) {
    if (item == null) {
      return Future.error("数据为空");
    }
    if (item.mediaType == null ||
        StringUtils.isEmpty(item.getFolderNameStr())) {
      return Future.error("文件找不到");
    }
    Map<String, dynamic> paramsMap = {
      "authId": UserRepository.getInstance().authId ?? "",
      // "hsn":_hsn ?? "",
      "picname": item.folderName,
      "picsize": item?.getSize() ?? "",
      "picstorage": item?.getStorage() ?? "",
      "picurl": item?.netUrl ?? "",
      "type": item?.mediaType?.getParamsValue() ?? "",
      "videopic": item?.videoNetCover ?? "",
      "videotime": item?.videoDuration ?? 0,
    };

    print("准备上传测试参数: ${paramsMap}");
    Completer<UploadMediaLibraryItemBean> completer = Completer();
    // return;
    VgHttpUtils.get(_UPLOAD_MEDIA_LIBRARY_API,
        params: paramsMap,
        callback: BaseCallback(onSuccess: (val) {
          // VgToastUtils.toast(AppMain.context, "上传成功");
          completer.complete(item);
        }, onError: (msg) {
          // VgToastUtils.toast(AppMain.context, msg);
          completer.completeError(msg);

        }));
    return completer.future;
  }
}
